package com.exception;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception ex) {
		CustomException ce;
		ex.printStackTrace();
		System.out.println(ex.getClass().getName());
		String msg = "";
		String backurl;
		// 判断ex异常类型是否为CustomException,如果是就将其赋给CustomException对象，如果不是new一个未知异常
		//ex.printStackTrace();
		if (ex instanceof CustomException) {
			msg = ex.getMessage();
			ce = (CustomException) ex;
		} else if (ex instanceof MyBatisSystemException) {
			msg = "数据库异常请联系管理员";
			ce = new CustomException(msg);
		}

		else if (ex instanceof CannotGetJdbcConnectionException) {
			msg = "数据库异常请联系管理员";
			ce = new CustomException(msg);
		}

		else if (ex instanceof SQLException) {
			msg = "数据库语句异常请联系管理员";
			ce = new CustomException(msg);
		}else if(ex instanceof ArithmeticException){
			msg = "添加失败，回滚";
			ce = new CustomException(msg);
		}
		else if (ex instanceof MySQLIntegrityConstraintViolationException){
			msg = "添加失败，已存在";
			ce = new CustomException(msg);
		}else if(ex instanceof UnauthorizedException){
			msg = "权限不足";
			ce = new CustomException(msg);
		}

		else {
			msg = "未知异常";
			ce = new CustomException("未知异常");
		}
		// 将错误信息放入请求作用域中
		request.setAttribute("message", ce.getMessage());
		try {
			// 进行页面的跳转，跳转到错误信息页面
			System.out.println(request.getContextPath() + "----" + request.getRequestURI());
			backurl = msg.equals("权限不足")?"home.jsp":"page/arrive"+request.getRequestURI();
			request.setAttribute("msg", msg);
			System.out.println(msg+" " + ce.getMessage());
			request.setAttribute("backurl", backurl);
			request.getRequestDispatcher("/templates/error/error.html").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
		return new ModelAndView();
	}
}